<script setup lang="ts">
import { useRouter, useRoute } from 'vue-router';
import { checkedCartGet } from '@/services/goods.ts';
import { informationGet } from '@/services/index.ts';
import { purchasePost, submitOrderPost } from '@/services';
import type { AddressDefault, SettlementList } from '@/types';

const $router = useRouter();
const $route = useRoute();
const settlementList = ref<SettlementList[]>([]);
const showPopup = ref(false);
const buyerRemark = reactive({
  remark: '',
  cartId: '',
});
const addressDefault = ref<AddressDefault>({
  id: '',
  shippingAddressDetail: '',
  shippingMobile: '',
  shippingPerson: '',
  defaultFlag: '',
});

const bankInfo = ref({});

const onAddressClick = () => {
  if ($route.query.goodsId) {
    sessionStorage.setItem(
      'addressData',
      JSON.stringify({
        type: 'buyNow',
        amount: $route.query.amount,
        goodsId: $route.query.goodsId,
      }),
    );
    $router.push({
      path: '/address',
    });
  } else {
    sessionStorage.setItem(
      'addressData',
      JSON.stringify({
        type: 'joinCart',
      }),
    );
    $router.push({ path: '/address' });
  }
};
const totals = computed(() => {
  return settlementList.value.reduce(
    (total: any, item: any) => {
      return {
        allCurrentPrice: (total.allCurrentPrice += item.cartItemList.reduce((a: any, b: any) => {
          return a + b.amount * b.currentPrice;
        }, 0)),
        allDiscountPrice: (total.allDiscountPrice += item.cartItemList.reduce((a: any, b: any) => {
          return a + b.amount * b.discountPrice;
        }, 0)),
      };
    },
    { allCurrentPrice: 0, allDiscountPrice: 0 },
  );
});

const onRemarkClick = (props: any) => {
  buyerRemark.cartId = props.cartId;
  if (props.buyerRemark) {
    buyerRemark.remark = props.buyerRemark;
  } else {
    buyerRemark.remark = '';
  }
  showPopup.value = !showPopup.value;
};

const onSureClick = () => {
  settlementList.value = settlementList.value.map((item: any) => {
    return {
      ...item,
      buyerRemark: item.cartId === buyerRemark.cartId ? buyerRemark.remark : item.buyerRemark,
    };
  });
  showPopup.value = false;
};
const onSubmitClick = async () => {
  if (!addressDefault.value) {
    showToast('请选择收货地址');
    return;
  }
  const subOrderReqInfos = settlementList.value.map((item: any) => {
    return {
      supplierId: item.supplierId,
      supplierName: item.supplierName,
      orderGoodsVoList: item.cartItemList,
      buyerRemark: item.buyerRemark,
    };
  });
  const customerShippingDetailVo = {
    shippingAddressDetail: addressDefault.value.shippingAddressDetail,
    shippingMobile: addressDefault.value.shippingMobile,
    shippingPerson: addressDefault.value.shippingPerson,
  };

  const params = {
    customerInvoiceVo: bankInfo.value,
    subOrderReqInfos,
    customerShippingDetailVo,
  };
  let { err, message } = await submitOrderPost(params);
  if (err) {
    showToast(err);
  } else {
    showToast(message);
    $router.push({ path: '/allOrder' });
  }
};

const addressData = async () => {
  const { data, err } = await informationGet();
  if (err) {
    showToast(err);
    return;
  }
  // 地址
  if ($route.query.customerShippingId) {
    addressDefault.value = data.customerShippingDetailList.find(
      (item: any) => item.customerShippingId === $route.query.customerShippingId,
    );
  } else {
    addressDefault.value = data.customerShippingDetailList.find(
      (item: any) => item.defaultFlag === 'YES',
    );
  }

  bankInfo.value = {
    bankAccount: data.bankAccount,
    depositBank: data.depositBank,
    invoiceTitle: data.invoiceTitle,
    invoiceType: data.invoiceType,
    registeredAddress: data.registeredAddress,
    registeredPhone: data.registeredPhone,
    taxpayerId: data.taxpayerId,
  };
};
const loadData = async () => {
  // 有 goodsId 就是立即购买跳转来的
  const { data, err } = $route.query.goodsId
    ? await purchasePost({
      amount: $route.query.amount,
      goodsId: $route.query.goodsId,
    })
    : await checkedCartGet();
  await addressData();
  if (err) {
    showToast(err);
    return;
  }
  settlementList.value = data.list;
};
onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="settlement_container">
    <div v-if="addressDefault" class="set_top">
      <svg-icon icon-class="address" size="1.4em" />
      <div class="top_address" @click="onAddressClick">
        <div class="address_box">
          <van-text-ellipsis rows="2" :content="addressDefault.shippingAddressDetail" />
          <div class="address_photo">
            <van-text-ellipsis
              rows="1"
              :content="`${addressDefault.shippingPerson} ${addressDefault.shippingMobile}`"
            />
          </div>
        </div>
        <svg-icon icon-class="right" size="1.3em" />
      </div>
    </div>
    <div v-else @click="onAddressClick" class="top_none">
      <div class="top_none_address">
        <svg-icon icon-class="address" size="1.4em" />
        <div class="top_none_icon">
          <van-text-ellipsis rows="1" content="请选择收货地址" />
        </div>
      </div>
      <svg-icon icon-class="right" size="1.3em" />
    </div>
    <div class="set_shop_box" v-for="item in settlementList" :key="item.id">
      <div class="goods_top">
        <svg-icon icon-class="shop" size="1.3em" />
        <div class="goods_company">{{ item.supplierName }}</div>
      </div>
      <div class="goods_box" v-for="cartItem in item.cartItemList" :key="cartItem.id">
        <van-image :src="cartItem.goodsImg?.split(',')[0]" round />
        <div class="goods_spc">
          <div class="goods_name">
            <van-text-ellipsis :content="cartItem.goodsName" />
          </div>
          <div class="goods_level">
            <van-text-ellipsis rows="4" :content="cartItem.goodsSpec" />
          </div>
        </div>
        <div class="goods_price">
          <div v-if="cartItem.discountPrice !== cartItem.currentPrice">
            <div class="price_num curPrice">{{ `￥${cartItem.discountPrice}` }}</div>
            <div class="price_num disPrice">{{ `￥${cartItem.currentPrice}` }}</div>
          </div>
          <div v-else class="price_num curPrice">{{ `￥${cartItem.discountPrice}` }}</div>
          <div class="price_num amount">{{ `x${cartItem.amount}` }}</div>
        </div>
      </div>
      <div class="goods_remarks">
        <div>订单备注:</div>
        <div class="remarks_text" @click="onRemarkClick(item)">
          <div v-if="item.buyerRemark" class="remarks_exist">
            <van-text-ellipsis rows="1" :content="item.buyerRemark" />
          </div>
          <div v-else class="remarks_none">请输入</div>
          <svg-icon icon-class="right" size="1.3em" />
        </div>
      </div>
    </div>
    <div style="width: 100%; height: 1px"></div>
  </div>
  <van-popup v-model:show="showPopup" position="bottom" :style="{ maxHeight: '70%' }">
    <div class="settlement_popup">
      <div class="popup_title">备注</div>
      <van-field
        v-model="buyerRemark.remark"
        rows="4"
        autosize
        type="textarea"
        maxlength="200"
        placeholder="请输入备注"
        show-word-limit
      />
      <van-button @click="onSureClick" color="#E89000" type="primary" block round>确定</van-button>
    </div>
  </van-popup>
  <van-submit-bar placeholder>
    <template #button>
      <div class="submit_bar">
        <div
          class="submit_price"
          v-if="totals.allCurrentPrice.toFixed(2) !== totals.allDiscountPrice.toFixed(2)"
        >
          <div class="price_num price_current">合计：￥{{ totals.allCurrentPrice.toFixed(2) }}</div>
          <div class="price_num">
            <div class="price_text">折后合计:</div>
            <div class="price_icon">￥</div>
            <div class="price_disPrice">{{ totals.allDiscountPrice.toFixed(2) }}</div>
          </div>
        </div>
        <div v-else class="no-price">
          <div class="price_num">
            <div class="price_text">合计:</div>
            <div class="price_icon">￥</div>
            <div class="price_disPrice">{{ totals.allDiscountPrice.toFixed(2) }}</div>
          </div>
        </div>
        <van-button @click="onSubmitClick" plain type="primary">确认提交</van-button>
      </div>
    </template>
  </van-submit-bar>
</template>

<style scoped lang="scss">
.submit_bar {
  height: 100%;
  display: flex;
  align-items: center;

  .price_num {
    display: flex;
    justify-content: flex-end;
  }

  .price_current {
    font-size: 12px;
    font-weight: 400;
    color: #787878;
  }

  .price_text {
    font-size: 12px;
    font-weight: 400;
    color: #454545;
  }

  .price_icon {
    font-size: 12px;
    font-weight: 400;
    color: #e86600;
  }

  .price_disPrice {
    font-size: 15px;
    font-weight: 500;
    color: #e86600;
  }

  .submit_price {
    height: 100%;
    margin-right: 8px;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .no-price {
    height: 100%;
    margin-right: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  :deep(.van-button) {
    width: 90px;
    height: 42px;
    color: #fff;
    background: #e89000;
    border: 1px solid #e89000;
  }
}

.settlement_container {
  width: 100%;
  min-height: calc(100vh - 50px);
  background: #f6f6f6;

  .set_top {
    height: 90px;
    padding: 8px 16px;
    margin-bottom: 8px;
    display: flex;
    background: white;

    .top_address {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .address_box {
        width: 260px;
        height: 100%;
        padding-left: 9px;
        font-size: 16px;
        font-weight: 500;
        color: #222222;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .address_photo {
          font-size: 14px;
          font-weight: 400;
          color: #787878;
        }
      }
    }
  }

  .top_none {
    width: 100%;
    height: 56px;
    padding: 16px;
    display: flex;
    justify-content: space-between;
    background: white;

    .top_none_address {
      font-size: 16px;
      font-weight: 500;
      display: flex;
      color: #222222;

      .top_none_icon {
        margin-left: 8px;
      }
    }
  }

  .set_shop_box {
    width: 100%;
    margin-bottom: 8px;
    background: white;

    .goods_top {
      width: 100%;
      height: 40px;
      padding-left: 20px;
      display: flex;
      align-items: center;

      .goods_company {
        font-size: 14px;
        font-weight: 500;
        margin-left: 8px;
        color: #222222;
      }
    }

    .goods_box {
      width: 100%;
      height: 104px;
      padding: 8px 16px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .van-image {
        width: 88px;
        height: 88px;
        margin: 0 8px;
        border-radius: 8px;
      }

      .goods_spc {
        width: 170px;
        height: 100%;

        .goods_name {
          font-size: 13px;
          font-weight: 500;
          color: #000000;
        }

        .goods_level {
          font-size: 12px;
          font-weight: 400;
          color: #787878;
        }
      }

      .goods_price {
        height: 100%;

        .price_num {
          display: flex;
          justify-content: flex-end;
        }

        .curPrice {
          font-size: 14px;
          font-weight: 500;
          color: #e86600;
        }

        .disPrice {
          font-size: 12px;
          font-weight: 400;
          color: #aaaaaa;
          text-decoration: line-through;
        }

        .amount {
          font-size: 10px;
          font-weight: 400;
          color: #aaaaaa;
        }
      }
    }

    .goods_remarks {
      width: 100%;
      height: 54px;
      padding: 0 16px;
      font-size: 13px;
      font-weight: 400;
      color: #454545;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .remarks_text {
        width: 260px;
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }

      .remarks_exist {
        width: 250px;
        height: 17px;
      }

      .remarks_none {
        font-size: 13px;
        font-weight: 400;
        color: #aaaaaa;
      }
    }
  }
}

.settlement_popup {
  width: 100%;
  height: 100%;
  padding: 0 16px;

  .van-field {
    background: #f6f6f6;
    border-radius: 4px;
  }

  .van-button {
    height: 40px;
    margin-top: 48px;
    margin-bottom: 16px;
  }

  .popup_title {
    width: 100%;
    height: 40px;
    font-size: 16px;
    font-weight: 600;
    color: #000000;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
